/**
* @Description: 订货分类 - 新增
* @author  tangbin
* @date 2023/3/12
*/

<template>
  <div class="mh100">
    <div class="page-container">
      <el-form ref="form" :model="form" :rules="rules" label-width="92px">
        <div class="split-content-info" id="ruleTop">
          <!-- 标题 -->
          <div class="split-content-title clearfix">
            <div class="split-title">
              <span style="display:inline-block; background-color: #1890FF;margin-bottom: -2px; margin-right: 8px; width: 3px; height: 14px"></span>
              <span style="display: inline-block; color: #333333; font-size: 16px;">基本信息</span>
            </div>
          </div>
          <el-row>
            <el-col :span="8">
              <el-form-item label="分类名称:" prop="name">
                <el-input
                  placeholder="请输入"
                  v-model="form.name"
                  clearable
                  maxlength="50"
                  size="small"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="状态:" prop="status">
                <el-select v-model="form.status" placeholder="请选择" size="small" clearable style="width:100%">
                  <el-option
                    v-for="item in dict.type.order_class_status"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="16" style="padding-right:0px;">
              <el-form-item label="备注:">
                <el-input v-model="form.remark" :autosize="{ minRows: 3, maxRows: 12}" type="textarea" placeholder="请输入内容" maxlength="500" show-word-limit></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 模块分割线 -->
        <div class="split-line"></div>
        <!-- 模块分割线 -->
        <div class="split-content-info" :style="{minHeight: height + 'px'}">
          <div class="split-content-title clearfix" style="margin-bottom: 0px;">
            <div class="split-title">
              <span style="display:inline-block; background-color: #1890FF;margin-bottom: -2px; margin-right: 8px; width: 3px; height: 14px"></span>
              <span style="display: inline-block; color: #333333; font-size: 16px;">订货规则</span>
            </div>
            <div class="clearfix" style="padding-bottom: 10px">
              <el-button style="float: right;" type="primary" icon="el-icon-plus" size="small" @click="addRule">添加规则</el-button>
            </div>
          </div>
          <!-- <div class="clearfix" style="padding-bottom: 10px">
            <el-button style="float: right;" type="primary" icon="el-icon-plus" size="small" @click="addRule">添加规则</el-button>
          </div> -->
          <div>
            <!-- :style="{minHeight: height + 'px'}" -->
            <el-table
              :data="form.orderClassRuleList" 
              ref="filterTable"
              :inline="true"
              :label-position="labelPosition"
            >
              <el-table-column label="序号" align="left" type="index" width="60"/>
              <el-table-column label="规则类型" align="left" prop="ruleType" min-width="176">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.ruleType" placeholder="请选择" min-width="176" size="small" @change="ruleChange(scope.row)">
                    <el-option v-for="item in dict.type.order_rule_type" :key="item.value" :label="item.label" :value="item.value"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="订货品种数从" align="left" prop="ordersFrom" min-width="130">
                <template slot-scope="scope">
                  <el-input
                    placeholder="请输入"
                    v-model="scope.row.ordersFrom"
                    clearable
                    maxlength="5"
                    size="small"
                    :disabled="scope.row.disabled"
                    @blur="ordersFromBlur(scope.row, $event)"
                    oninput="this.value= this.value.match(/\d+/) ? this.value.match(/\d+/)[0] : '';"
                  />
                </template>
              </el-table-column>
              <el-table-column label="订货品种数至" align="left" prop="ordersTo" min-width="130">
                <template slot-scope="scope">
                  <el-input
                    placeholder="请输入"
                    v-model="scope.row.ordersTo"
                    clearable
                    maxlength="5"
                    size="small"
                    :disabled="scope.row.disabled"
                    @blur="ordersToBlur(scope.row, $event)"
                    oninput="this.value= this.value.match(/\d+/) ? this.value.match(/\d+/)[0] : '';"
                  />
                </template>
              </el-table-column>
              <!-- show-overflow-tooltip -->
              <el-table-column label="收货地区" align="left" prop="receiveArea" min-width="260">
                <template slot-scope="scope">
                  <el-tooltip placement="top">
                    <div slot="content" style="min-width: 160px; max-height:236px; overflow: auto;">
                      <ul style="list-style-type: none; padding-left:0;">
                        <li style="height: 22px; line-height: 22px; font-size: 14px; font-weight: 400;" v-for="item in scope.row.areaList" :key="item.id">{{ item.areaName }}</li>
                      </ul>
                    </div>
                    <span style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ scope.row.receiveArea ? scope.row.receiveArea.slice(0, 15) + '...' : '' }}</span>
                  </el-tooltip>
                  <!-- <div style="width: 260px; height= 400px; overflow: auto;">
                    <el-popover
                    placement="right"
                    width="400"
                    trigger="hover">
                    <el-table :data="scope.row.areaList" height="360">
                      <el-table-column align="center" property="areaName" label="地址"></el-table-column>
                    </el-table>
                    <span style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" slot="reference">{{ scope.row.receiveArea }}</span>
                  </el-popover>
                  </div> -->
                  
                </template>
              </el-table-column>
              <el-table-column label="最低起运总量" align="left" prop="minShipmentTotal" min-width="130">
                <template slot-scope="scope">
                  <el-input
                    placeholder="请输入"
                    v-model="scope.row.minShipmentTotal"
                    clearable
                    maxlength="5"
                    size="small"
                    :disabled="scope.row.disabled"
                    oninput="this.value= this.value.match(/\d+/) ? this.value.match(/\d+/)[0] : '';"
                    @blur="scope.row.minShipmentTotal=$event.target.value"
                  />
                </template>
              </el-table-column>
              <el-table-column label="最低免运费总量" align="left" prop="minFreefreightTotal" min-width="130">
                <template slot-scope="scope">
                  <el-input
                    placeholder="请输入"
                    v-model="scope.row.minFreefreightTotal"
                    clearable
                    maxlength="5"
                    size="small"
                    :disabled="scope.row.disabled"
                    oninput="this.value= this.value.match(/\d+/) ? this.value.match(/\d+/)[0] : '';"
                    @blur="scope.row.minFreefreightTotal=$event.target.value"
                  />
                </template>
              </el-table-column>
              <el-table-column label="最低免运费总金额(元)" align="left" prop="minFreefreightAmount" min-width="170">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.minFreefreightAmount"
                    maxlength="10"
                    clearable
                    size="small"
                    :disabled="scope.row.disabled"
                    oninput="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
                    @blur="scope.row.minFreefreightAmount=$event.target.value"
                    placeholder="请输入"
                  >
                    <!-- <span
                      slot="suffix"
                      style="font-size: 12px; color: #333; line-height: 32px"
                      >元</span
                    > -->
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" align="left" class-name="small-padding fixed-width" width="220">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleConfigReceiveArea(scope.row)">配置收货地区</el-button>
                  <el-button size="mini" type="text" icon="el-icon-key" @click="handleDel(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

        </div>
      </el-form>
      <div class="h84_line"></div>
      <div class="bottom-btn">
        <div class="bottom-locate" >
          <el-button type="default" @click="cancel">取消</el-button>
          <el-button type="primary" :loading="saveloading" @click="save">确认</el-button>
        </div>
      </div>


      <el-dialog :title="title" :visible.sync="open" width="720px" append-to-body :close-on-click-modal="false">
        <div class="dialog-main">
          <div class="dialog-left">
            <el-form :inline="true">
              <el-form-item label="地区名称">
                <!-- v-model="form.categoryName" -->
                <el-input
                  placeholder="请输入"
                  clearable
                  v-model="filterText"
                  size="small"
                >
                  <!-- <el-button slot="append" type="primary" icon="el-icon-search" size="mini">搜索</el-button> -->
                </el-input>
              </el-form-item>
              <el-form-item label="" style="margin-bottom: 0;">
                <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
                <!-- <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox> -->
                <!-- <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox> -->
                <div class="left-area">
                  <el-tree
                    :data="menuOptions"
                    show-checkbox
                    ref="menu"
                    node-key="id"
                    :check-strictly="false"
                    empty-text="暂无数据"
                    :check-on-click-node="true"
                    :props="defaultProps"
                    @check="treeCheck"
                    :filter-node-method="filterNodeArea"
                  ></el-tree>
                </div>
              </el-form-item>
            </el-form>
          </div>
          <div class="dialog-right">
            <span class="right-top">已选地区</span>
            <!-- :row-style="{height: '30px'}" -->
            <el-table
              class="right-bottom"
              :data="currentRow ? currentRow.areaList : []" 
              :inline="true"
              :border="false"
              
            >
            <!--  show-overflow-tooltip -->
              <el-table-column label="" align="left" prop="areaName" width="340px">
                <template slot-scope="scope">
                  <div class="table-column-area">
                    <span class="table-column-area-span">{{ scope.row.areaName }}</span>
                    <el-button class="table-column-area-btn" size="mini" type="text" icon="el-icon-circle-close" @click="deleteArea(scope.row)"></el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelDialog">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>

    </div>
  </div>
 </template>

<script>
import { isEmpty } from 'element-ui/src/utils/util';
import {orderGoodsSave, getDivisionTree} from '@/api/basic/orderGoodsClas.js'

export default {
  name: 'OrderGoodsClassifyAdd',
  dicts: ['order_class_status', 'order_rule_type'],
  // dicts: ['sys_normal_disable', 'sys_user_sex'],
  data() {
    return {
      // tableHeight: 700,
      height: 130,
      title: '配置收货地区',
      filterText: '', // 搜索地区
      menuExpand: false, // 是否展开折叠
      menuNodeAll: false, // 是否全选
      menuOptions: [], // 所有地区列表列表
      defaultProps: {
        children: "children",
        label: "name"
      },
      open: false, // 是否显示弹窗
      saveloading: false,
      labelPosition: "right",     // 表单label对齐方式
      form: {
        name: undefined, // 分类名称
        status: 'ENABLE', // 状态
        remark: undefined, // 备注
        orderClassRuleList: [], // 订货规则
        // menuCheckStrictly: true, // 是否父子联动
      },
      // currentRoleModel: undefined, // 当前规则
      currentRow: undefined, // 当前row
      areaList: [], // 当前的地区
      rules: {
        name: [
        {required: true, message: "请输入分类名称", trigger: "blur"}
        ]
      },
      // isFirst: false,
    }
  },
  created() {
    
  },
  mounted() {
    this.getDivisionTree();
    // 解决表格设置固定高度导致列设置fixed后重新进来会错行问题
    this.tableHeight();
  },
  activated() {
    this.getDivisionTree();
    // 解决表格设置固定高度导致列设置fixed后重新进来会错行问题
    this.tableHeight();
  },
  watch: {
    filterText(val) {
      this.$refs.menu.filter(val);
    }
  },
  methods: {

    tableHeight() {
      this.$nextTick(() => {
        let height = document.body.clientHeight - 90 - 40;// - 62 - 20;
        // 查询表单高度
        let s_height = document.getElementById('ruleTop').clientHeight;
        // 按钮容器高度
        // let btns_height = document.getElementById('comTabel').clientHeight;
        // 计算表格的高度
        this.height = height - s_height - 20 - 64;
      });
    },

    /**
     * 获取行政区划数据
     */
    getDivisionTree() {
      getDivisionTree({name: ''}).then(res => {
        // console.log('res=', res);
        if (res.code === 200) {
          const list = res.data;
          if (list && list.length > 0) {
            this.menuOptions = list[0].children;
            // console.log('menuOptions=', this.menuOptions);
            this.menuOptions && this.menuOptions.forEach(item => {
              // 子集的数量
              // console.log('item=', item);
              // 省下面有多少个市
              this.$set(item, 'childrenCount', item.children ? item.children.length : 0);
              // console.log('name=', item.name);
              // 遍历市
              item.children && item.children.forEach(ent => {
                this.$set(ent, 'childrenCount', ent.children ? ent.children.length : 0);
              });
            });
          }
        }
      }).catch(err => {

      });
    },

    /**
     * 添加规则
     * 规则类型
     * 1. 符合可订货：订货品种数从、订货品种数至、收货地址(可为空)、最低起运总量、最低免运费总量、最低免运费总金额 均可填写。
     * 2. 付款不可订货：收货地址(必填)，订货品种数从、订货品种数至、最低起运总量、最低免运费总量、最低免运费总金额 均不可填写。
     */
    addRule() {
      let params = {
        ruleType: 'CONFORMCANORDERED', // 规则类型
        ordersFrom: undefined, // 订货品种数从
        ordersTo: undefined,  // 订货品种数至
        receiveArea: undefined, // 收货地区
        minShipmentTotal: undefined, // 最低起运总量
        minFreefreightTotal: undefined, // 最低免运费总量
        minFreefreightAmount: undefined, // 最低免运费总金额
        disabled: false, // 当时符合不可订货的时候，订货品种数从、订货品种数至、最低起运总量、最低免运费总量、最低免运费总金额 均不可填
        areaList: []
      };
      this.form.orderClassRuleList.push(params);
    },

    /**
     * 订货规则 选择规则类型的时候调用
     * @param {*} row 
     */
    ruleChange(row) {
      // console.log('row=', row);
      if (row.ruleType == 'NONCONFORMCANORDERED') { // 符合不可订货
        row.disabled = true;
        row.ordersFrom = undefined;
        row.ordersTo = undefined;
        row.minShipmentTotal = undefined;
        row.minFreefreightTotal = undefined;
        row.minFreefreightAmount = undefined;
      } else { // 符合可订货
        row.disabled = false;
      }
    },

    /**
     * 订货品种数从 失去焦点
     * @param {*} row 
     */
    ordersFromBlur(row, event) {
      row.ordersFrom = event.target.value;
      let ordersTo = parseInt(row.ordersTo);
      let ordersFrom = parseInt(row.ordersFrom);
      if (ordersFrom < 0) {
        this.$modal.msgError("订货品种数从 不能小于0！");
      }
      // if (ordersTo !== 0 && ordersFrom >= ordersTo) {
      //   this.$modal.msgError("订货品种数区间不正确！");
      // }
    },

    /**
     * 订货品种数至
     * @param {*} row 
     */
    ordersToBlur(row, event) {
      // scope.row.minShipmentTotal=$event.target.value
      row.ordersTo = event.target.value;
      let ordersTo = parseInt(row.ordersTo);
      let ordersFrom = parseInt(row.ordersFrom);
      if (ordersTo < 0) {
        this.$modal.msgError("订货品种数至 不能小于0！");
        return;
      }
      if (ordersFrom > ordersTo) {
        this.$modal.msgError("订货品种数区间不正确！");
        return;
      }
    },

    /**
     * 配置收货地区
     */
    handleConfigReceiveArea(row) {
      this.currentRow = row;
      this.areaList = JSON.parse(JSON.stringify(row.areaList));
      // this.currentRow = JSON.parse(JSON.stringify(row));
      // console.log('currentRow=', this.currentRow);
      this.open = true;
      this.$nextTick(()=>{
        this.$refs.menu.setCheckedKeys([]);
      });

      if (this.currentRow.areaList && this.currentRow.areaList.length > 0) {
        this.currentRow.areaList.forEach((item) => {
          // console.log('item.areacode=', item.areaCode);
          this.$nextTick(()=>{
            this.$refs.menu.setChecked(item.areaCode, true ,true);
          });
        });
      } else {
        this.$nextTick(()=>{
          this.$refs.menu.setCheckedKeys([]);
        });
      }
    },

    /**
     * 过滤属性结构的数据
     * @param {*} value 
     * @param {*} data 
     */
    filterNodeArea(value, data) {
      if (!value) {
        return true;
      }
      return data.name.indexOf(value) !== -1;
    },

    /**
     * 树权限（展开/折叠）
     * @param {*} value 
     * @param {*} type 
     */
     handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    
    /**
     * 树权限（全选/全不选）
     * @param {*} value 
     * @param {*} type 
     */
    // handleCheckedTreeNodeAll(value, type) {
    //   if (type == 'menu') {
    //     this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
    //   }
    // },
    
    /**
     * 树权限（父子联动）
     * @param {*} value 
     * @param {*} type 
     */
    // handleCheckedTreeConnect(value, type) {
    //   if (type == 'menu') {
    //     this.form.menuCheckStrictly = value ? true: false;
    //   }
    // },

    /**
     * 点击tree
     * @param {*} item 
     * @param {*} de 
     */
     treeCheck(item, data) {
      // console.log('item=', item);
      // console.log('data=', data);
      let selected = false; // 是否选中
      if (data.checkedKeys.indexOf(item.id) !== -1) {
        // console.log('选中');
        selected = true;
      }

      if (selected == false) {
        this.unselectedNode(item);
        return;
      }

      const resArea = this.checkParentLevel(item, data);
      console.log('resArea=', resArea);
      if (resArea.currentLevel == resArea.totalLevel) { // 当前层级 跟总层级相等 表示 叶子节点
        // 当前层级跟总层级数一样
        this.currentEqualTotalLevel(item, resArea);
      } else if (resArea.currentLevel == resArea.totalLevel - 1) { // 倒数第二级
        this.currentEqualTotalLevelTwo(item, resArea);
        
      } else if (resArea.currentLevel == resArea.totalLevel - 2) { // 倒数第三极
        this.currentEqualTotalLevelOne(item, resArea);
      }
    },

    /**
     * 取消选中节点
     */
    unselectedNode(item) {
      console.log('------取消选中节点-----');
      if (item.level == 1) { // 当前节点是一级
        if (item.childrenCount == 0) { // 没有子集，比如 香港
          this.removeCheckedArea(item.id);
        } else {
          item.children && item.children.forEach(model => {
            let list = this.currentRow.areaList.filter(ent => {
              if (model.id == ent.areaCode) {
                return ent;
              }
            });
            if (list && list.length > 0) {
              this.removeCheckedArea(list[0].areaCode);
            }
            model.children && model.children.forEach(ent => {
              let list = this.currentRow.areaList.filter(e => {
                if (ent.id == e.areaCode) {
                  return e;
                }
              });
              if (list && list.length > 0) {
                this.removeCheckedArea(list[0].areaCode);
              }
            });
          });
          this.removeCheckedArea(item.id);
        }
      } else if (item.level == 2) { // 当前节点是二级
        console.log('cur=', item);
        // 根据父节点id得到父节点选中的子节点的个数
        const count = this.getChildCount(item.parentId);
        console.log('count=====', count);
        if (count == 0) {// 表示没有子节点 或者 选中了所有的子节点
          const parentItem = this.getAreaNodeData(item.parentId); // 获取父节点信息
          console.log('当前是二级=', count, '; total=', parentItem.childrenCount);
          let selectedNode = this.getSelectedNodeData(item.parentId);
          console.log('查找上级=', selectedNode);
          if (selectedNode) {
            // 找到了父级，表示子集是全选
            this.removeCheckedArea(item.parentId);
            parentItem.children.forEach(ent => {
              if (ent.id !== item.id) {
                let model = {
                  areaCode: ent.id, 
                  parentId: ent.parentId, 
                  areaName: parentItem.name + '-' + ent.name
                };
                this.addArea(model);
              }
            });
          } else {
            if (item.children && item.children.length > 0) {
              item.children.forEach(ent => {
                // console.log('删除=', ent.id + '-'+ent.name);
                this.removeCheckedArea(ent.id);
              });
            }
            this.removeCheckedArea(item.id);
          }
        } else {
          if (item.children && item.children.length > 0) {
            // console.log('有子');
            item.children.forEach(ent => {
              // console.log('删除=', ent.id + '-'+ent.name);
              this.removeCheckedArea(ent.id);
            });
          }
          this.removeCheckedArea(item.id);
          
        }
      } else if (item.level == 3) {
        console.log('cur=', item);
        const count = this.getChildCount(item.parentId); // 三级的父级(二级)
        if(count !== 0) {
          this.removeCheckedArea(item.id);
          return;
        }
        console.log('count =', count);
        const parentTwoItem = this.getAreaNodeData(item.parentId); // 获取父节点信息(二级)
        const parentFirstItem = this.getAreaNodeData(parentTwoItem.parentId); // 一级
        console.log('parentTwoItem=', parentTwoItem);
        console.log('parentFirstItem=', parentFirstItem);
        let selectedNode = this.getSelectedNodeData(parentFirstItem.id); // 一级有没有被选中
        if (selectedNode) {
          this.removeCheckedArea(parentFirstItem.id);
          parentFirstItem && parentFirstItem.children.forEach(ent => {
            if (ent.id !== parentTwoItem.id) {
              let model = {
                areaCode: ent.id, 
                parentId: ent.parentId, 
                areaName: parentFirstItem.name + '-' + ent.name
              };
              this.addArea(model);
            }
          });
          parentTwoItem && parentTwoItem.children.forEach(ent => {
            if (ent.id !== item.id) {
              let model = {
                areaCode: ent.id, 
                parentId: ent.parentId, 
                areaName: parentFirstItem.name + '-' + parentTwoItem.name + '-' + ent.name
              };
              this.addArea(model);
            }
          });
        } else {
          let selectedNode = this.getSelectedNodeData(parentTwoItem.id); // 一级有没有被选中
          if (selectedNode) {
            this.removeCheckedArea(parentTwoItem.id);
            parentTwoItem && parentTwoItem.children.forEach(ent => {
            if (ent.id !== item.id) {
              let model = {
                areaCode: ent.id, 
                parentId: ent.parentId, 
                areaName: parentFirstItem.name + '-' + parentTwoItem.name + '-' + ent.name
              };
              this.addArea(model);
            }
          });
          }
        }
      }
    },

    /**
     * 当前层级等总层级
     * @param {*} curRow 当前点击的节点
     * @param {*} area 
     */
    currentEqualTotalLevel(curRow, area) {
      console.log('当前层级等总层级====');
      console.log('curRow=', curRow);
      console.log('area=', area);
      let name = '';
      let id = undefined;
      let parentId = undefined;
      let level = undefined;
      if (curRow.level == 1) {
        // this.removeChildrenNode(curRow.parentId);
        name = area.name1;
        id = area.area1.id;
        level = area.area1.level;
        parentId = area.area1.parentId;
      } else if (curRow.level == 2) {
        name = area.name1;
        const count = this.getChildCount(curRow.parentId) + 1;
        if (area.area1.childrenCount == count) { // 表示选中的父级中的所有子集
          this.removeChildrenNode(curRow.parentId);
          id = curRow.parentId;
          level = area.area1.level;
          parentId = area.area1.parentId;
        } else {
          name = name + '-' + area.name2;
          id = curRow.id;
          level = curRow.level;
          parentId = curRow.parentId;
        }
        // console.log('count =', count);
      } else if (curRow.level == 3) {
        const districtCount = this.getChildCount(curRow.parentId) + 1; // 区县数量
        // console.log('districtCount=', districtCount);
        if (districtCount == area.area2.childrenCount) {
          // 选中了，某个城市的所有区县
          // console.log('选中了，某个城市的所有区县');
          const cityCount = this.getChildCount(area.area2.parentId) + 1;
          if (cityCount == area.area1.childrenCount) {
            // 选中了所有的城市
            // console.log('选中了所有的城市');
            this.unselectedNode(area.area1);
            name = area.name1;
            id = area.area1.id;
            level = area.area1.level;
            parentId = area.area1.parentId;
          } else {
            this.removeChildrenNode(curRow.parentId);
            name = area.name1 + '-' + area.name2;
            id = area.area2.id;
            level = area.area2.level;
            parentId = area.area2.parentId;
          }
        } else {
          // console.log('不是全部');
          name = area.name1 + '-' + area.name2 + '-' + area.name3;
          id = curRow.id;
          level = curRow.level;
          parentId = curRow.parentId;
        }
      }
      let model = {
        areaCode: id, 
        level: level,
        parentId: parentId, 
        areaName: name
      };
      console.log('model=', model);
      this.addArea(model);
    },

    /**
     * 当前层级跟总层级相差1
     * @param {*} curRow 
     * @param {*} area 
     */
    currentEqualTotalLevelTwo(curRow, area) {
      console.log('当前层级跟总层级相差1');
      console.log('curRow=', curRow);
      // console.log('area=', area);
      let name = '';
      let id = undefined;
      let parentId = undefined;
      let level = undefined;
      if (curRow.level == 1) {
        this.removeChildrenNode(curRow.id);
        name = area.name1;
        id = area.area1.id;
        level = area.area1.level;
        parentId = area.area1.parentId;
      } else if (curRow.level == 2) {
        name = area.name1;
        const count = this.getChildCount(curRow.parentId) + 1;
        if (area.area1.childrenCount == count) { // 表示选中的父级中的所有子集
          this.removeChildrenNode(curRow.parentId);
          id = curRow.parentId;
          level = area.area1.level;
          parentId = area.area1.parentId;
        } else {
          this.removeChildrenNode(curRow.id);
          name = name + '-' + area.name2;
          id = curRow.id;
          level = curRow.level;
          parentId = curRow.parentId;
        }
        // console.log('count =', count);
      } else if (curRow.level == 3) {
        const districtCount = this.getChildCount(curRow.parentId) + 1; // 区县数量
        // console.log('districtCount=', districtCount);
        if (districtCount == area.area2.childrenCount) {
          // 选中了，某个城市的所有区县
          // console.log('选中了，某个城市的所有区县');
          const cityCount = this.getChildCount(area.area2.parentId) + 1;
          if (cityCount == area.area1.childrenCount) {
            // 选中了所有的城市
            // console.log('选中了所有的城市');
            this.unselectedNode(area.area1);
            name = area.name1;
            id = area.area1.id;
            level = area.area1.level;
            parentId = area.area1.parentId;
          } else {
            // console.log('55555');
            this.removeChildrenNode(curRow.parentId);
            name = area.name1 + '-' + area.name2;
            id = area.area2.id;
            level = area.area2.level;
            parentId = area.area2.parentId;
            area.area3 = undefined;
          }
        } else {
          // console.log('不是全部');
          name = area.name1 + '-' + area.name2 + '-' + area.name3;
          id = curRow.id;
          level = curRow.level;
          parentId = curRow.parentId;
        }
      }

      let model = {
        areaCode: id, 
        level: level,
        parentId: parentId, 
        areaName: name
      };
      console.log('model=', model);
      this.addArea(model);
    },

    /**
     * 当前层级跟总层级相差2
     * @param {*} curRow 
     * @param {*} area 
     */
     currentEqualTotalLevelOne(curRow, area) {
      console.log('当前层级跟总层级相差2');
      // console.log('curRow=', curRow);
      // console.log('area=', area);
      let name = curRow.name;
      let id = curRow.id;
      let level = curRow.level;
      let parentId = curRow.parentId;

      if (curRow.level == 1) {
        this.removeAllChildrenNode(curRow.id);

      }

      curRow.children && curRow.children.forEach(item => {
        let list = this.areaList.filter(ent => {
          if (item.id == ent.areaCode) {
            return ent;
          }
        });
        if (list && list.length > 0) {
          this.removeCheckedArea(list[0].areaCode);
        }
        item.children && item.children.forEach(ent => {
          let list = this.areaList.filter(e => {
            if (ent.id == e.areaCode) {
              return e;
            }
          });
          if (list && list.length > 0) {
            this.removeCheckedArea(list[0].areaCode);
          }
        });
      });
      let model = {
        areaCode: id, 
        level: level,
        parentId: parentId, 
        areaName: name
      };
      console.log('model=', model);
      this.addArea(model);
    },

    /**
     * 根据地区id获取地区数据
     * @param {*} id 
     */
    getAreaNodeData(id) {
      // console.log('进来了id=', id);
      // console.log('this.menuOptions=', this.menuOptions);
      // 有没有查询到省份
      let list = this.menuOptions && this.menuOptions.filter(e => {
        // console.log('e.id=', e.id, '; id=', id);
        if (e.id == id) {
          return e;
        }
      });
      // console.log('22222222');
      // console.log('list=', list);
      let arr = [];
      if (this.menuOptions && list && list.length == 0) {
        // console.log('11111');
        this.menuOptions.some(item => {
          arr = item.children && item.children.filter(e => {
            if (e.id == id) {
              // console.log('id=', id, '; e=', e);
              return e;
            }
          });
          
          if (arr && arr.length > 0) {
            // console.log('666666');
            return true;
          } else {
            
          }
          // console.log('888888');
          
        });
        // let arr = this.menuOptions.children && this.menuOptions.children.filter(e => {
        //   console.log('id1=', e.id, 'id=', id);
        //   if (e.id == id) {
        //     return e;
        //   }
        // });
        // console.log('arr=', arr);
        // console.log('99999999');
        if (arr && arr.length > 0) {
          return arr[0];
        } else {
          // console.log('没有找到=', id);
          let ret = false;
          arr = [];
          if (this.menuOptions && this.menuOptions.length > 0) {
            this.menuOptions.some(prov => {
              prov.children && prov.children.some(cityObj => {
                // console.log('name=', cityObj.name);
                arr = cityObj.children && cityObj.children.filter(e => {
                  if (e.id == id) {
                    // console.log('找到了鹅鹅鹅id=', id, '; e=', e);
                    ret = true;
                    return e;
                  }
                });
                // console.log('arr====', arr);
                return ret;
              });
              // console.log('909090909');
              return ret;

            });
            // console.log('5656565656=', arr);
            if (arr && arr.length > 0) {
              // console.log('有了==', arr[0]);
              return arr[0];
            } else {
              return undefined;
            }
          }
          return undefined;
        }
      } else {
        // console.log('4444444');
        if (list && list.length > 0) {
          return list[0];
        } else {
          return undefined;
        }
      }
    },

    /**
     * 根据父节点id得到父节点选中的子节点的个数
     * @param {*} parentId 
     */
    getChildCount(parentId) {
      const list = this.currentRow.areaList.filter(e => {
        if (e.parentId == parentId) {
          return e;
        }
      });
      return list && list.length;
    },

    /**
     * 得到选中节点
     * @param {*} id 
     */
    getSelectedNodeData(id) {
      // console.log('id=', id);
      const list = this.currentRow.areaList.filter(e => {
        // console.log('e.areacode=', e.areaCode , 'id=', id);
        if (e.areaCode == id) {
          return e;
        }
      });
      // console.log('list=', list);
      if (list && list.length > 0) {
        return list[0];
      }
      return undefined;
    },

    /**
     * 删除子节点数据 删除儿子节点
     * @param {*} parentId 
     */
    removeChildrenNode(parentId) {
      this.currentRow.areaList = this.currentRow.areaList.filter(e => {
        // slice
        if (e.parentId != parentId) {
          return e;
        }
      });
    },

    /**
     * 删除后代节点
     * @param {*} parentId 
     */
    removeAllChildrenNode(parentId) {
      this.currentRow.areaList = this.currentRow.areaList.filter(e => {
        // slice
        if (e.parentId.slice(0, 3) != parentId.slice(0, 3)) {
          return e;
        }
      });
    },


    /**
     * 添加地区
     * @param {*} item 
     */
    addArea(item) {
      const newList = this.currentRow.areaList.filter(e => {
        if (e.areaCode == item.areaCode) {
          return e;
        }
      });
      if (!newList ||newList.length == 0) {
        this.currentRow.areaList.push(item);
      }
    },

    /**
     * 从已经选中的区域 删除
     * @param {*} code 
     */
    removeCheckedArea(code) {
      let model = null;
      this.currentRow.areaList.some((item) => {
        if (item.areaCode === code) {
          model = item;
          return true;
        }
      });
      if (model !== null) {
        // console.log('找到了数据');
        this.currentRow.areaList.splice(this.currentRow.areaList.indexOf(model), 1);
      }
    },

    /**
     * 从列表中删除
     * @param {*} row 
     */
    deleteArea(row) {
      this.removeCheckedArea(row.areaCode);
      this.$nextTick(()=>{
        this.$refs.menu.setChecked(row.areaCode, false ,true);
      });
    },

    /**
     * 根据当晚地区id 获取的相关参数
     * @param {*} curId 
     * @param {*} data 
     */
    checkParentLevel(row, data) {
      let curId = row.id;
      let name1 = ''; // 一级名称
      let area1 = undefined; // 一级对象
      let name2 = ''; // 二级名称
      let area2 = undefined; // 二级对象
      let name3 = ''; // 三级名称
      let area3 = undefined; // 三级级对象
      let totalLevel = 0; // 总级别
      let currentLevel = 0; // 当前级别
      let direcCities = ['北京市', '上海市', '天津市', '重庆市'];

      if (row.level == 3) { // 当前层级是3级
        currentLevel = row.level;
        totalLevel = row.level;
        let twoItem = this.getAreaNodeData(row.parentId);
        let oneItem = undefined;
        if (twoItem) {
          oneItem = this.getAreaNodeData(twoItem.parentId);
        }
        name1 = oneItem && oneItem.name;
        area1 = oneItem;
        name2 = twoItem && twoItem.name;
        area2 = twoItem;
        name3 = row.name;
        area3 = row;
      } else if (row.level == 2) { // 当前是二级
        currentLevel = row.level;
        totalLevel = row.level;
        if (row.children && row.children.length > 0) {
          totalLevel = row.level + 1;
        }
        let oneItem = this.getAreaNodeData(row.parentId);
        name1 = oneItem && oneItem.name;
        area1 = oneItem;
        name2 = row.name;
        area2 = row;
      } else if (row.level == 1) { // 当前是1级
        currentLevel = row.level;
        totalLevel = row.level;
        if (row.children && row.children.length > 0) {
          totalLevel = row.level + 1;
          row.children.some(ent => {
            if (ent.children && ent.children.length > 0) {
              totalLevel = row.level + 2;
              return true;
            }
          });
        }
        name1 = row.name;
        area1 = row;
      }

      return {
          currentLevel: currentLevel, // 当前层级
          totalLevel: totalLevel, // 总层级
          name1: name1,
          area1: area1,
          name2: name2,
          area2: area2,
          name3: name3,
          area3: area3
        };
    },

    /**
     * 删除
     */
    handleDel(row) {
      // console.log('row=', row);
      this.form.orderClassRuleList.splice(this.form.orderClassRuleList.indexOf(row), 1);
    },

    /**
     * 取消弹窗
     */
    cancelDialog() {
      this.open = false;
      this.currentRow.areaList = JSON.parse(JSON.stringify(this.areaList));
      this.handleCheckedTreeExpand(false, 'menu');
    },

    /**
     * 弹窗点击确认
     */
    submitForm() {
      this.open = false;
      // this.currentRow.areaList = this.areaList;
      this.currentRow.receiveArea = undefined;
      this.areaList = [];
      // console.log('this.currentRow.areaList=', this.currentRow.areaList);
      // return;
      let list = [];
      if (this.currentRow.areaList && this.currentRow.areaList.length > 0) {
        let index = 0;
        this.currentRow.areaList.some((item) => {
          if (index >= 5) {
            return true;
          }
          list.push(item.areaName);
          index = index + 1;
        });
        this.currentRow.receiveArea = list.toString();
      }
      this.handleCheckedTreeExpand(false, 'menu');
    },

    cancel() {
      const obj = { path: "/basicData/orderGoodsClassify" };
      this.$tab.closeOpenPage(obj);
    },

    /**
     * 保存
     */
    save() {
      if (!this.form.orderClassRuleList || this.form.orderClassRuleList.length <= 0) {
        this.$modal.msgError("请添加订货规则！");
        return;
      }
      // console.log('form=', this.form);
      /*
      ordersFrom: 0, // 订货品种数从
        ordersTo: 0,  // 订货品种数至
        receiveArea: undefined, // 收货地区
        minShipmentTotal: 0, // 最低起运总量
        minFreefreightTotal: 0, // 最低免运费总量
        minFreefreightAmount: 0.00, // 最低免运费总金额
       */
      let ret = false;
      this.form.orderClassRuleList.some((item) => {


        // 1. 符合可订货：订货品种数从、订货品种数至、收货地址(可为空)、最低起运总量、最低免运费总量、最低免运费总金额 均可填写。
        // 2. 付款不可订货：收货地址(必填)，订货品种数从、订货品种数至、最低起运总量、最低免运费总量、最低免运费总金额 均不可填写。
        let ordersFrom = Number(item.ordersFrom == undefined ? 0 : item.ordersFrom);
        let ordersTo = Number(item.ordersTo == undefined ? 0 : item.ordersTo);
        // console.log('ordersFrom=', ordersFrom, '; ordersTo=', ordersTo);
        // CONFORMCANORDERED 符合可订货；NONCONFORMCANORDERED 符合不可订货
        if (item.ruleType == 'CONFORMCANORDERED' && ordersFrom < 0 || ordersTo < 0) {
          this.$modal.msgError("订货品种数不能小于0！");
          ret = true;
          return true;
        }

        // 符合可订货
        if (item.ruleType == 'CONFORMCANORDERED' && ordersFrom > ordersTo) {
          // console.log('额我认为二');
          this.$modal.msgError("订货品种数区间不正确！");
          ret = true;
          return true;
        }



        // 符合不可订货 地区为必填； 符合可订货 时 地区为可填
        if (item.ruleType == 'NONCONFORMCANORDERED' && item.areaList.length <= 0) {
          this.$modal.msgError("请配置收货地区！");
          ret = true;
          return true;
        }

        // console.log('minFreefreightTotal=', item.minFreefreightTotal);
        let minShipmentTotal = item.minShipmentTotal == undefined ? 0 : item.minShipmentTotal;
        let minFreefreightTotal = item.minFreefreightTotal == undefined ? 0 : item.minFreefreightTotal;
        let minFreefreightAmount = item.minFreefreightAmount == undefined ? 0 : item.minFreefreightAmount;
        // 符合不可订货 后面的几个数
        if (item.ruleType == 'CONFORMCANORDERED' && Number(minShipmentTotal) == 0 && Number(minFreefreightTotal) == 0 && Number(minFreefreightAmount) == 0.00) {
          this.$modal.msgError('最低起运总量、最低免运费总量、最低免运费总金额 必须有一个不为0');
          ret = true;
          return true;
        }
      });
      
      if (ret == true) {
        return;
      }
      // console.log('form=', this.form);
      // return;
      this.$refs['form'].validate(valid => {
        if (!valid) {
          this.disabled = false;
          return;
        }
        orderGoodsSave(this.form).then(res => {
            // console.log('res=', res);
            if (res) {
                this.$modal.msgSuccess("添加成功");
                // this.open = false;
                this.disabled = false;
                // this.onRefreshTable();
                const obj = { path: "/basicData/orderGoodsClassify" };
                this.$tab.closeOpenPage(obj);
              }
          }).catch(err => {
            this.disabled = false;
          });
      });
    },
  },
}
</script>

<style lang="scss" scoped>
.dialog-main {
  display: flex;
  flex-direction: row;

  .dialog-left {
    flex: 1;
    // background-color: red;
    display: flex;
    flex-direction: column;
    ::v-deep .el-form-item {
      margin-bottom: 8px;
    }
    .left-area {
      display: inline-block;
      width: 330px;
      // width:100%;
      height: 300px;
      margin-top: 5px;
      border: 1px solid #e5e6e7;
      background: #FFFFFF none;
      border-radius:4px;
      overflow: auto;
    }
  }
  .dialog-right {
    flex: 1;
    // background-color: orange;
    .right-top {
      margin-top: 9px;
      margin-left: 10px;
      margin-bottom: 54px;
      display: inline-block;
    }
    ::v-deep.el-table__header-wrapper {
      border: 0;
      height:0;
    }
    ::v-deep.el-table__cell {
      border: 0;
    }
    
    ::v-deep.el-table .cell {
      line-height: 28.5px;
    }
    ::v-deep .el-table--enable-row-transition .el-table__body td.el-table__cell {
      padding: 0;
    }
    .right-bottom {
      height: 312px;
      overflow: auto;
      // background-color: lightcoral;
      
      .table-column-area {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        // background-color: lightblue;
        height: 28px;
        flex
        .table-column-area-span {
          // flex: 3;
          height: 28.5px;
          font-size: 14px;
          font-weight: 400;
        }
        
        .table-column-area-btn {
          // flex: 1;
        }
      }
    }
  }
}
</style>